package org.feng.listener;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;
import org.feng.manager.CustomDictManager;
import org.feng.vo.CustomDictExcelVo;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义字典监听器
 *
 * @author feng
 */
@Slf4j
public class CustomDictExcelListener extends AnalysisEventListener<CustomDictExcelVo> {

    private final CustomDictManager customDictManager;

    /**
     * 数据缓存
     */
    private final List<CustomDictExcelVo> excelVoCache = new ArrayList<>();

    /**
     * 统计本次导入的总数据条数
     */
    private long count;

    /**
     * 批次数量：100
     */
    private static final int BATCH_COUNT = 100;

    public CustomDictExcelListener(CustomDictManager customDictManager) {
        this.customDictManager = customDictManager;
    }


    @Override
    public void invoke(CustomDictExcelVo customDictExcelVo, AnalysisContext analysisContext) {
        // 分批次入库
        if(excelVoCache.size() == BATCH_COUNT) {
            if(customDictManager.importBatch(excelVoCache)) {
                count = count + BATCH_COUNT;
                log.info("导入数据100条");
            }

            // 清空缓存
            excelVoCache.clear();
        }

        // 数据加入到缓存
        excelVoCache.add(customDictExcelVo);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if(CollUtil.isNotEmpty(excelVoCache)) {
            if (customDictManager.importBatch(excelVoCache)) {
                count = count + excelVoCache.size();
                log.info("导入数据{}条", excelVoCache.size());
            }

            // 清空缓存
            excelVoCache.clear();
        }

        log.info("导入数据共计{}条", count);
    }
}
